'use strict';

module.exports = {
  up: async (queryInterface, Sequelize) => {
    const now = new Date();
    
    // 定义所有表配置
    const configs = [
      // 1. 租户表配置
      {
        code: 'tenants',
        name: '租户管理',
        description: '系统租户信息管理',
        table_name: 'tenants',
        api_path: '/tenants',
        fields: [
          { 
            key: 'id', 
            label: 'ID', 
            type: 'text', 
            table: { hidden: true }, 
            search: { searchable: false }, 
            form: { creatable: false, editable: false } 
          },
          { 
            key: 'name', 
            label: '租户名称', 
            type: 'text', 
            table: { width: 150, sortable: true, fixed: 'left' }, 
            search: { searchable: true, searchType: 'like', quickSearch: true }, 
            form: { creatable: true, editable: true, required: true, rules: [{ required: true, message: '请输入租户名称' }], placeholder: '请输入租户名称' } 
          },
          { 
            key: 'subdomain', 
            label: '子域名', 
            type: 'text', 
            table: { width: 150 }, 
            search: { searchable: true, searchType: 'like' }, 
            form: { creatable: true, editable: false, required: true, rules: [{ required: true, message: '请输入子域名' }], placeholder: '请输入子域名，如：tenant1', componentProps: { addonAfter: '.yourdomain.com' } } 
          },
          { 
            key: 'planId', 
            label: '套餐', 
            type: 'select', 
            table: { width: 200, render: 'relation', relationField: 'plan.name' }, 
            search: { searchable: true, searchType: 'equal' }, 
            form: { 
              creatable: true, 
              editable: true, 
              required: true, 
              rules: [{ required: true, message: '请选择套餐' }],
              optionsConfig: { 
                source: 'api', 
                apiUrl: '/plans', 
                labelField: 'name', 
                valueField: 'id',
                labelTemplate: '{name} ({code}) - ¥{price}/月'
              },
              placeholder: '请选择套餐'
            } 
          },
          { 
            key: 'defaultPassword', 
            label: '默认密码', 
            type: 'text', 
            table: { hidden: true }, 
            search: { searchable: false }, 
            form: { 
              creatable: true, 
              editable: true, 
              required: false, 
              placeholder: '新用户的默认密码（留空则使用 Pass123456）',
              componentProps: { placeholder: '默认: Pass123456' }
            } 
          },
          { 
            key: 'status', 
            label: '状态', 
            type: 'select', 
            table: { 
              width: 100, 
              align: 'center',
              optionsConfig: { 
                source: 'dictionary', 
                dictionaryCode: 'tenant_status' 
              }
            }, 
            search: { 
              searchable: true, 
              searchType: 'equal',
              optionsConfig: { 
                source: 'dictionary', 
                dictionaryCode: 'tenant_status' 
              }
            }, 
            form: { 
              creatable: true, 
              editable: true, 
              required: true,
              optionsConfig: { 
                source: 'dictionary', 
                dictionaryCode: 'tenant_status' 
              },
              initialValue: 'trial'
            } 
          },
          { 
            key: 'trialEndsAt', 
            label: '试用结束时间', 
            type: 'datetime', 
            table: { width: 160, format: 'YYYY-MM-DD HH:mm' }, 
            search: { searchable: false }, 
            form: { creatable: true, editable: true, required: false, componentProps: { showTime: true } } 
          },
          { 
            key: 'subscriptionEndsAt', 
            label: '订阅结束时间', 
            type: 'datetime', 
            table: { width: 160, format: 'YYYY-MM-DD HH:mm' }, 
            search: { searchable: false }, 
            form: { creatable: true, editable: true, required: false, componentProps: { showTime: true } } 
          },
          { 
            key: 'createdAt', 
            label: '创建时间', 
            type: 'datetime', 
            table: { width: 180, sortable: true, format: 'YYYY-MM-DD HH:mm:ss' }, 
            search: { searchable: false }, 
            form: { creatable: false, editable: false } 
          }
        ]
      },
      // 2. 套餐表配置
      {
        code: 'plans',
        name: '套餐管理',
        description: '系统套餐计划管理',
        table_name: 'plans',
        api_path: '/plans',
        fields: [
          { key: 'id', label: 'ID', type: 'text', table: { hidden: true }, search: { searchable: false }, form: { creatable: false, editable: false } },
          { key: 'name', label: '套餐名称', type: 'text', table: { width: 150, sortable: true }, search: { searchable: true, searchType: 'like', quickSearch: true }, form: { creatable: true, editable: true, required: true, rules: [{ required: true, message: '请输入套餐名称' }] } },
          { key: 'code', label: '套餐编码', type: 'text', table: { width: 120 }, search: { searchable: true, searchType: 'like' }, form: { creatable: true, editable: false, required: true, rules: [{ required: true, message: '请输入套餐编码' }] } },
          { key: 'description', label: '描述', type: 'textarea', table: { width: 200, ellipsis: true }, search: { searchable: false }, form: { creatable: true, editable: true } },
          { key: 'price', label: '价格', type: 'number', table: { width: 100, align: 'right' }, search: { searchable: false }, form: { creatable: true, editable: true, required: true, componentProps: { min: 0, precision: 2 } } },
          { key: 'isActive', label: '状态', type: 'select', table: { width: 100, align: 'center', render: 'tag' }, search: { searchable: true }, form: { creatable: true, editable: true, options: [{ label: '启用', value: true }, { label: '禁用', value: false }] } },
          { key: 'createdAt', label: '创建时间', type: 'datetime', table: { width: 180, sortable: true, format: 'YYYY-MM-DD HH:mm:ss' }, search: { searchable: false }, form: { creatable: false, editable: false } }
        ]
      },
      // 3. 权限表配置
      {
        code: 'permissions',
        name: '权限管理',
        description: '系统权限资源管理',
        table_name: 'permissions',
        api_path: '/permissions',
        fields: [
          { key: 'id', label: 'ID', type: 'text', table: { hidden: true }, search: { searchable: false }, form: { creatable: false, editable: false } },
          { key: 'resource', label: '资源', type: 'text', table: { width: 150, sortable: true }, search: { searchable: true, searchType: 'like', quickSearch: true }, form: { creatable: true, editable: false, required: true, rules: [{ required: true, message: '请输入资源标识' }] } },
          { key: 'action', label: '操作', type: 'text', table: { width: 120 }, search: { searchable: true, searchType: 'like' }, form: { creatable: true, editable: false, required: true, rules: [{ required: true, message: '请输入操作类型' }] } },
          { key: 'description', label: '描述', type: 'text', table: { width: 200, ellipsis: true }, search: { searchable: false }, form: { creatable: true, editable: true } },
          { key: 'module', label: '模块', type: 'text', table: { width: 120 }, search: { searchable: true, searchType: 'like' }, form: { creatable: true, editable: true } },
          { key: 'createdAt', label: '创建时间', type: 'datetime', table: { width: 180, sortable: true, format: 'YYYY-MM-DD HH:mm:ss' }, search: { searchable: false }, form: { creatable: false, editable: false } }
        ]
      },
      // 4. 操作日志表配置
      {
        code: 'audit_logs',
        name: '操作日志',
        description: '系统操作记录日志',
        table_name: 'audit_logs',
        api_path: '/audit-logs',
        fields: [
          { key: 'id', label: 'ID', type: 'text', table: { hidden: true }, search: { searchable: false }, form: { creatable: false, editable: false } },
          { key: 'userId', label: '操作用户', type: 'text', table: { width: 200, render: 'relation', relationField: 'user.email' }, search: { searchable: true, searchType: 'equal' }, form: { creatable: false, editable: false } },
          { key: 'action', label: '操作类型', type: 'select', table: { width: 120, align: 'center', optionsConfig: { source: 'dictionary', dictionaryCode: 'audit_log_action' } }, search: { searchable: true, searchType: 'equal', quickSearch: true, optionsConfig: { source: 'dictionary', dictionaryCode: 'audit_log_action' } }, form: { creatable: false, editable: false, optionsConfig: { source: 'dictionary', dictionaryCode: 'audit_log_action' } } },
          { key: 'resource', label: '操作资源', type: 'text', table: { width: 150 }, search: { searchable: true, searchType: 'like' }, form: { creatable: false, editable: false } },
          { key: 'resourceId', label: '资源ID', type: 'text', table: { width: 200, ellipsis: true }, search: { searchable: true }, form: { creatable: false, editable: false } },
          { key: 'ipAddress', label: 'IP地址', type: 'text', table: { width: 150 }, search: { searchable: true }, form: { creatable: false, editable: false } },
          { key: 'createdAt', label: '操作时间', type: 'datetime', table: { width: 180, sortable: true, format: 'YYYY-MM-DD HH:mm:ss' }, search: { searchable: false }, form: { creatable: false, editable: false } }
        ]
      },
      // 5. 登录日志表配置
      {
        code: 'login_logs',
        name: '登录日志',
        description: '用户登录记录',
        table_name: 'login_logs',
        api_path: '/login-logs',
        fields: [
          { key: 'id', label: 'ID', type: 'text', table: { hidden: true }, search: { searchable: false }, form: { creatable: false, editable: false } },
          { key: 'userId', label: '用户', type: 'text', table: { width: 150, render: 'relation', relationField: 'user.email' }, search: { searchable: true, searchType: 'equal' }, form: { creatable: false, editable: false } },
          { key: 'email', label: '登录邮箱', type: 'text', table: { width: 200 }, search: { searchable: true, searchType: 'like', quickSearch: true }, form: { creatable: false, editable: false } },
          { key: 'status', label: '登录状态', type: 'select', table: { width: 120, align: 'center', optionsConfig: { source: 'dictionary', dictionaryCode: 'login_status' } }, search: { searchable: true, searchType: 'equal', optionsConfig: { source: 'dictionary', dictionaryCode: 'login_status' } }, form: { creatable: false, editable: false, optionsConfig: { source: 'dictionary', dictionaryCode: 'login_status' } } },
          { key: 'ipAddress', label: 'IP地址', type: 'text', table: { width: 150 }, search: { searchable: true }, form: { creatable: false, editable: false } },
          { key: 'userAgent', label: '浏览器信息', type: 'text', table: { width: 250, ellipsis: true }, search: { searchable: false }, form: { creatable: false, editable: false } },
          { key: 'createdAt', label: '登录时间', type: 'datetime', table: { width: 180, sortable: true, format: 'YYYY-MM-DD HH:mm:ss' }, search: { searchable: false }, form: { creatable: false, editable: false } }
        ]
      }
    ];

    // 批量插入配置
    for (const config of configs) {
      // 先删除已存在的配置（强制替换）
      await queryInterface.bulkDelete('table_configs', { code: config.code }, {});
      
      // 插入新配置
      await queryInterface.bulkInsert('table_configs', [{
        id: Sequelize.literal('UUID()'),
        code: config.code,
        name: config.name,
        description: config.description,
        table_name: config.table_name,
        api_path: config.api_path,
        fields: JSON.stringify(config.fields),
        actions: JSON.stringify({
          create: config.code === 'audit_logs' || config.code === 'login_logs' ? false : true,
          update: config.code === 'audit_logs' || config.code === 'login_logs' ? false : true,
          delete: true,
          batchDelete: true,
          export: true
        }),
        table_props: JSON.stringify({
          size: 'middle',
          rowKey: 'id',
          bordered: false,
          pagination: { pageSize: 10, showSizeChanger: true, showQuickJumper: true },
          rowSelection: true,
          scroll: { x: 1200 }
        }),
        permissions: JSON.stringify({
          view: `${config.code.replace('_', '-')}:read`,
          create: `${config.code.replace('_', '-')}:create`,
          update: `${config.code.replace('_', '-')}:update`,
          delete: `${config.code.replace('_', '-')}:delete`
        }),
        status: true,
        created_by: null,
        updated_by: null,
        created_at: now,
        updated_at: now
      }], {});
    }
  },

  down: async (queryInterface) => {
    const codes = ['tenants', 'plans', 'permissions', 'audit_logs', 'login_logs'];
    for (const code of codes) {
      await queryInterface.bulkDelete('table_configs', { code }, {});
    }
  }
};

